<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginUser" label-width="0">
      <h3 class="title">{{ currentUserType.value }}登陆</h3>
      <el-form-item prop="username">
        <el-input v-model="loginUser.account" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginUser.password" placeholder="密码" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login(loginUser)">登录</el-button>
        <el-button type="primary" @click="router.push({path: '/register'})">注册</el-button>
        <el-button type="primary" @click="switchLogin()">切换为{{ switchLoginSpan.value }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import type {LoginDTO, ResponseInterface} from "@/model/type";
import {UserType} from "@/model/type";
import {ref} from "vue";
import {getEnterpriseInfoByTokenAPI, getStudentInfoByTokenAPI, loginAPI} from "@/api/UserAPI";
import router from "@/router";
import {getLatestResumeNormalInfoAPI} from "@/api/ResumeAPI";

let switchLoginSpan = ref(UserType.ENTERPRISE)
let currentUserType = ref(UserType.STUDENT)
let loginUser = ref<LoginDTO>({account: "", password: "", userType: ""})

async function login(loginUser: LoginDTO) {
  loginUser.userType = currentUserType.value.type
  console.log(loginUser)
  const r: ResponseInterface = await loginAPI(loginUser)
  if (r.code == 200) {
    let tokenStr = r.data;
    localStorage.setItem("token", tokenStr)
    let r2: ResponseInterface;
    let resumeResponse: ResponseInterface;
    if (loginUser.userType == UserType.STUDENT.type) {
      r2 = await getStudentInfoByTokenAPI(tokenStr)
      resumeResponse = await getLatestResumeNormalInfoAPI(tokenStr)
      localStorage.setItem("resumeId", resumeResponse.data.id)
    } else {
      r2 = await getEnterpriseInfoByTokenAPI(tokenStr)
    }
    if (r2.code == 200) {
      localStorage.setItem("user", JSON.stringify(r2.data))
    }
    if (currentUserType.value.type == UserType.STUDENT.type) {
      await router.push({path: "/home"})
    } else {
      await router.push({path: "/enterprise_home/info"})
    }
  }
}

function switchLogin() {
  if (currentUserType.value.type == UserType.STUDENT.type) {
    switchLoginSpan.value = UserType.STUDENT
    currentUserType.value = UserType.ENTERPRISE
  } else {
    switchLoginSpan.value = UserType.ENTERPRISE
    currentUserType.value = UserType.STUDENT
  }
}
</script>

<style scoped>   .login-container {
  width: 400px;
  margin: 0 auto;
  padding-top: 60px;
}

.title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}
</style>